import { ThunkAction } from 'redux-thunk'
import { ICondition, IMovie } from "../../typings/interface"
import { movieActionEnums } from "../typings/movieEnums"
import * as actions from '../typings/movieTypes'
import MovieServices from '../../apis/movieServices'

export const delMovieAction = (payload: string): actions.delAction => ({
  type: movieActionEnums.DEL_MOVIE,
  payload
})

export const addMovieAction = (payload: IMovie): actions.addAction => ({
  type: movieActionEnums.ADD_MOVIE,
  payload
})

export const saveMovieAction = (payload: IMovie[]): actions.saveAction => ({
  type: movieActionEnums.SAVE_MOVIE,
  payload
})

export const setLoadingAction = (payload: boolean): actions.setLoadingAction => ({
  type: movieActionEnums.SET_LOADING,
  payload
})

export const setConditionAction = (payload: ICondition): actions.setConditionAction => ({
  type: movieActionEnums.SET_CONDITION,
  payload
})

// 异步action
export const getMovieAsyncAction = (payload: ICondition): ThunkAction<Promise<void>, any, any, actions.movieActions> => {
  return async (dispatch, getState) => {
    // 合并conditions
    dispatch(setConditionAction(payload))
    // 设置状态
    dispatch(setLoadingAction(true))
    const {movieState:{conditions}} = getState()
    // 查询数据
    const {data:{success,data}} = await MovieServices.queryMovie(conditions)
    if(data && success){
      const result = data.data
      // 设置movieAction
      dispatch(saveMovieAction(result))
    }
    // 设置状态
    dispatch(setLoadingAction(false))
  }
}

export const addMovieAsyncAction = (payload:IMovie):ThunkAction<Promise<void>, any, any, actions.movieActions> => {
  return async (dispatch, getState) => {
    // 设置状态
    dispatch(setLoadingAction(true))
    // 添加数据
    const {data:{data,success}} = await MovieServices.addMovie(payload)
    if(data && success){
      dispatch(getMovieAsyncAction({}))
    }
  }
}